﻿namespace Methods
{
    using System;

    class SelectionSortWithMethods
    {
        // 1.1.9.09. Write a method that returns the maximal element in a portion of array of integers starting at given index.
        // Using it write another method that sorts an array in ascending / descending order.

        public static int FindBiggest(int startIndex, int endIndex, int[] arr)
        {
            int biggest = int.MinValue;
            int indexOfBiggest = 0;
            for (int i = startIndex; i < endIndex; i++)
            {
                if (arr[i] > biggest)
                {
                    biggest = arr[i];
                    indexOfBiggest = i;
                }
            }
            return indexOfBiggest;
        }
        public static void SwapElements(int[] arr, int firstElement, int secondElement)
        {
            int temp = arr[firstElement];
            arr[firstElement] = arr[secondElement];
            arr[secondElement] = temp;
            // return arr;
        }
        public static int[] SelectionSort(int[] arr, bool ascend)
        {
            if (ascend == true)
            {
                for (int i = arr.Length - 1; i > 0; i--)
                {
                    int indexOfBiggest = FindBiggest(0, i, arr);

                    if (arr[indexOfBiggest] > arr[i])
                    {
                        SwapElements(arr, i, indexOfBiggest);
                    }
                }
            }
            else    // descend
            {
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    int indexOfBiggest = FindBiggest(i + 1, arr.Length, arr);

                    if (arr[indexOfBiggest] > arr[i])
                    {
                        SwapElements(arr, i, indexOfBiggest);
                    }
                }
            }

            return arr;
        }
        public static void PrintArr(int[] arr)
        {
            foreach (var item in arr)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }

        static void Main()
        {
            int[] arr = { 5, 3, 6, 0, 9, 9, 8, 3, 1, 3, 2 };

            bool ascend = true;
            PrintArr(SelectionSort(arr, ascend));

            bool descend = false;
            PrintArr(SelectionSort(arr, descend));
        }
    }
}